<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/07/18 12:37:09 $)
// $RCSfile: functions_calendarrender.php,v $ : $Revision: 1.13 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Render the Day View for Calendar
*/
function renderDayView($day = false, $onlyworkhours = false)
{
	global $dbCore, $_SWIFT;

	if (empty($day))
	{
		$day = edate("d-m-Y");
	}

	$daystore = explode("-", $day);

	$dateline = mktime(0,0,0,$daystore[1], $daystore[0], $daystore[2]);
	$prevday = $dateline-(1*60*60*24);
	$nextday = $dateline+(1*60*60*24);

	$_events = loadCalendarEvents($dateline, $nextday);

	// Load the staff schedule
	$_schedule = getStaffSchedule();

	if ($onlyworkhours == true)
	{
		$_prevdaytext = ' href="index.php?_m=teamwork&_a=calendar&calendartype=day&customday='. date("d-m-Y", $prevday) .'"';
		$_nextdaytext = ' href="index.php?_m=teamwork&_a=calendar&calendartype=day&customday='. date("d-m-Y", $nextday) .'"';
	} else {
		$_prevdaytext = ' href="#" onClick="javascript:switchGridTab(\'twday\', \'teamwork\');fetchData(\'twday\', \''. date("d-m-Y", $prevday) .'\');"';
		$_nextdaytext = ' href="#" onClick="javascript:switchGridTab(\'twday\', \'teamwork\');fetchData(\'twday\', \''. date("d-m-Y", $nextday) .'\');"';
	}

	// ======= HEADER =======
	$data .= '<table border="0" cellpadding="3" cellspacing="1" width="100%" class="'. iif($onlyworkhours==true, 'tborderround', 'tborder') .'"><tr><td class="row1"><span class="smalltext">
	<table border="0" cellpadding="2" cellspacing="0" width="100%"><tr><td width="1" align="left"><a'. $_prevdaytext .'><img src="'. $_SWIFT["themepath"] .'icon_back.gif" border="0" align="absmiddle" /></a></td>
	<td width="100%" align="center"><span class="ttexttitle">'. date("l, d F Y", $dateline) .'</span></td>
	<td width="1" align="right"><a'. $_nextdaytext .'><img src="'. $_SWIFT["themepath"] .'icon_forward.gif" border="0" align="absmiddle" /></a></td></tr></table><BR />';

	$data .= '<table border="0" cellpadding="0" cellspacing="0" width="100%" class="calborder">';
	$day = getStrDayRep(date("w", $dateline));
	$daycomp = $day."_enabled";

/*	if ($_schedule[$daycomp] == "1")
	{
		echo "Day Enabled<BR />";
	} else {
		echo "Day Not Enabled<BR />";
	}*/

	for ($ii=0; $ii<24; $ii++)
	{
		$formattedhour = sprintf("%02d:00", $ii);
		$tdclass = "calinactivehour";
	
		$hrdateline = mktime($ii,0,0,$daystore[1], $daystore[0], $daystore[2]);

		$opendateline = returnHourDateline($_schedule[$day."_open"], $dateline);
		$closedateline = returnHourDateline($_schedule[$day."_close"], $dateline);

/*		if ($opendateline < $hrdateline)
		{
			echo $formattedhour."Open is OK<BR />";
		} else {
			echo $formattedhour."Open Not OK<BR />";
		}

		if ($closedateline > $hrdateline)
		{
			echo $formattedhour."Close is OK<BR />";
		} else {
			echo $formattedhour."Close is NOT OK<BR />";
		}*/

		$_isworkhour = false;
		if ($_schedule[$daycomp] == "1" && $opendateline <= $hrdateline && $closedateline >= $hrdateline)
		{
			$tdclass = "calactivehour";
			$_isworkhour = true;
		}

		if ($onlyworkhours == true && !$_isworkhour && $_schedule[$day."_enabled"] == 1)
		{
			continue;
		}
 		$data .= '<tr class="'. $tdclass .'"><td width="60" style="PADDING: 3px;" class="calhrbg"><span class="tabletitle"><a href="index.php?_m=teamwork&_a=insertevent&startdateline='. $hrdateline .'">'. $formattedhour .'</a></span></td><td width="1" class="calendarsplitter"><img src="'. $_SWIFT["themepath"] .'space.gif" border="0" width="1" height="1" /></td><td width="100%">';
		$data .= renderHorizontalEventBlocks($_events, $hrdateline, ($hrdateline+3599));
 		$data .= '</td></tr>';

		if ($ii != 23)
		{
			$data .= '<tr height="1" class="calendarsplitter"><td colspan="3"><img src="'. $_SWIFT["themepath"] .'space.gif" border="0" width="1" height="1" /></td></tr>';
		}
	}
	$data .= '</table>';

	$data .= '</span></td></tr></table>';

	if ($onlyworkhours != true)
	{
		$data .= '<BR />';
	}

	return $data;
}

/**
* Render the Work Week View for Calendar
*/
function renderWorkWeekView($week = false, $loadentireweek = false)
{
	global $dbCore, $_SWIFT;

	if (empty($week))
	{
		$week = edate("d-m-Y");
	}

	$daystore = explode("-", $week);

	$dateline = mktime(0,0,0,$daystore[1], $daystore[0], $daystore[2]);
	$daysub = date("w", $dateline);

	if ($daysub != 1)
	{
		if ($daysub == 0)
		{
			// its a sunday, so we need to append one day to it..
			$startweekdateline = $dateline+86400;
			$eventdateline = $dateline;
		} else {
			$daysubt = $daysub-1;
			$startweekdateline = $dateline-($daysubt*86400);
		}
	} else {
		$startweekdateline = $dateline;
	}

	if (empty($eventdateline))
	{
		$eventdateline = $startweekdateline;
	}

	$prevweek = $dateline-(7 * 86400);
	$nextweek = $dateline+(7 * 86400);

	$_events = loadCalendarEvents($eventdateline, ($eventdateline+(7 * 86400)));
//	print_r($_events);

	// Load the staff schedule
	$_schedule = getStaffSchedule();

	if ($loadentireweek == true)
	{
		$caltype = "week";
	} else {
		$caltype = "workweek";
	}

	// ======= HEADER =======
	$data .= '<table border="0" cellpadding="3" cellspacing="1" width="100%" class="tborder"><tr><td class="row1"><span class="smalltext">
	<table border="0" cellpadding="2" cellspacing="0" width="100%"><tr><td width="1" align="left"><a href="#" onClick="javascript:switchGridTab(\'tw'. $caltype .'\', \'teamwork\');fetchData(\'tw'. $caltype .'\', \''. date("d-m-Y", $prevweek) .'\');"><img src="'. $_SWIFT["themepath"] .'icon_back.gif" border="0" align="absmiddle" /></a></td>
	<td width="100%" align="center"><span class="ttexttitle">[%REPTITLE%]</span></td>
	<td width="1" align="right"><a href="#" onClick="javascript:switchGridTab(\'tw'. $caltype .'\', \'teamwork\');fetchData(\'tw'. $caltype .'\', \''. date("d-m-Y", $nextweek) .'\');"><img src="'. $_SWIFT["themepath"] .'icon_forward.gif" border="0" align="absmiddle" /></a></td></tr></table><BR />';

	$data .= '<table border="0" cellpadding="0" cellspacing="0" width="100%" class="calborder">'.SWIFT_CRLF;

	$daylist = array();
	for ($ii=0; $ii<7; $ii++)
	{
		$day = getStrDayRep($ii);
		if ($_schedule[$day."_enabled"] == 1 || $loadentireweek == true)
		{
			$daylist[] = $ii;
		}
	}

	$colspan = 2+(count($daylist)*2);
	if (!count($daylist))
	{
		$splitwidth = 100;
	} else {
		$splitwidth = round(100/count($daylist));
	}

	$data .= '<tr class="calhrbg"><td width="60" style="PADDING: 3px;" class="calhrbg"><span class="tabletitle">&nbsp;</span></td><td width="1" class="calendarsplitter"><img src="'. $_SWIFT["themepath"] .'space.gif" border="0" width="1" height="1" /></td>'.SWIFT_CRLF;

	for ($kk=0; $kk<7; $kk++)
	{
		// Sunday
		if ($kk == 0)
		{
			$daydateline = $startweekdateline-86400;
		} else if ($kk == 1) {
			$daydateline = $startweekdateline;
		} else {
			$daydateline = $startweekdateline+(($kk-1)*86400);
		}

		if (in_array($kk, $daylist))
		{
			if ($kk == $daylist[0])
			{
				$startdaydateline = $daydateline;
			} else if ($kk == $daylist[count($daylist)-1]) {
				$enddaydateline = $daydateline;
			}
			
			$data .= '<td width="'. $splitwidth .'%" align="center">'.SWIFT_CRLF;
			$data .= '<span class="tabletitle">'. date("D, d M", $daydateline) .'</span>'.SWIFT_CRLF;
			$data .= '</td>'.SWIFT_CRLF;
			if ($kk != $daylist[count($daylist)-1])
			{
				$data .= '<td width="1" class="calendarsplitter"><img src="'. $_SWIFT["themepath"] .'space.gif" border="0" width="1" height="1" /></td>'.SWIFT_CRLF;
			}
		}
	}
	$data .= '</tr>'.SWIFT_CRLF;

	for ($ii=0; $ii<24; $ii++)
	{
		$formattedhour = sprintf("%02d:00", $ii);
		$tdclass = "calinactivehour";
		$data .= '<tr class="'. $tdclass .'"><td width="60" style="PADDING: 3px;" class="calhrbg"><span class="tabletitle">'. $formattedhour .'</span></td><td width="1" class="calendarsplitter"><img src="'. $_SWIFT["themepath"] .'space.gif" border="0" width="1" height="1" /></td>';

		for ($kk=0; $kk<7; $kk++)
		{
			// Sunday
			if ($kk == 0)
			{
				$daydateline = $startweekdateline-86400;
			} else if ($kk == 1) {
				$daydateline = $startweekdateline;
			} else {
				$daydateline = $startweekdateline+(($kk-1)*86400);
			}

			$day = getStrDayRep($kk);
//			echo $day."-".$_schedule[$day."_open"]."<BR />";
//			echo $day."-".$_schedule[$day."_close"]."<BR />";
			if (in_array($kk, $daylist))
			{
				$daycomp = $day."_enabled";
				$hrdateline = mktime($ii,0,0,date("m", $daydateline), date("d", $daydateline), date("Y", $daydateline));

				$opendateline = returnHourDateline($_schedule[$day."_open"], $daydateline);
				$closedateline = returnHourDateline($_schedule[$day."_close"], $daydateline);

				$tdclass = "calinactivehour";
				if ($_schedule[$daycomp] == "1" && $opendateline <= $hrdateline && $closedateline >= $hrdateline)
				{
					$tdclass = "calactivehour";
				}

				$verticalblocks = renderVerticalEventBlocks($_events, $hrdateline, ($hrdateline+3599), true, $_schedule);
 				$data .= '<td width="'. $splitwidth .'%" class="'. $tdclass .'"'. iif(empty($verticalblocks), ' style="CURSOR: pointer;" onMouseOver="javascript:this.className=\'calhrbg\';" onMouseOut="javascript:this.className=\''. $tdclass .'\';" onClick="javascript:window.location.href=\'index.php?_m=teamwork&_a=insertevent&startdateline='. $hrdateline .'\';" title="'. $_SWIFT["language"]["insertevent"] .'"') .'>';
 //				$data .= "Event: ".date("d m Y h:i:s A", $_events[8]["startdateline"])."<BR />";
//				$data .= "HR: ".date("d m Y h:i:s A", $hrdateline)."<BR />";
//				$data .= "Day: ".date("d m Y h:i:s A", $daydateline)."<BR />";
				$data .= $verticalblocks;
				$data .= '</td>';
				if ($kk != $daylist[count($daylist)-1])
				{
					$data .= '<td width="1" class="calendarsplitter"><img src="'. $_SWIFT["themepath"] .'space.gif" border="0" width="1" height="1" /></td>';
				}
				
			}
		}
	

/*		if ($opendateline < $hrdateline)
		{
			echo $formattedhour."Open is OK<BR />";
		} else {
			echo $formattedhour."Open Not OK<BR />";
		}

		if ($closedateline > $hrdateline)
		{
			echo $formattedhour."Close is OK<BR />";
		} else {
			echo $formattedhour."Close is NOT OK<BR />";
		}*/


		$data .= '</tr>';

		if ($ii != 23)
		{
			$data .= '<tr height="1" class="calendarsplitter"><td colspan="'. $colspan .'"><img src="'. $_SWIFT["themepath"] .'space.gif" border="0" width="1" height="1" /></td></tr>';
		}
	}
	$data .= '</table>';

	$data .= '</span></td></tr></table><BR />';

	return str_replace("[%REPTITLE%]", date("F d Y", $startdaydateline)." - ".date("F d Y", $enddaydateline), $data);
}

/**
* Render the Month View
*/
function renderMonthView($month = false)
{
	global $dbCore, $_SWIFT;

	if (empty($month))
	{
		$month = edate("1-m-Y");
	}

	$daystore = explode("-", $month);

	$dateline = mktime(0,0,0,$daystore[1], 1, $daystore[2]);
	$startday = date("w", $dateline);
	$daysub = date("w", $dateline);
	$currentmonth = date("m", $dateline);

	if ($daysub != 1)
	{
		if ($daysub == 0)
		{
			// its a sunday, so we need to adjust the timeline accordingly..
			$startweekdateline = $dateline-(6*86400);
		} else {
			$daysubt = $daysub-1;
			$startweekdateline = $dateline-($daysubt*86400);
		}
	} else {
		$startweekdateline = $dateline;
	}

	$weekdateline = $startweekdateline;

	$_events = loadCalendarEvents($dateline, getNextMonth($daystore[1], $daystore[2]));

	// Load the staff schedule
	$_schedule = getStaffSchedule();

//	echo date("d-m-Y", getPreviousMonth($daystore[1], $daystore[2]))."<BR />Current: ".$daystore[1]."--".$daystore[2];

	$data .= '<table border="0" cellpadding="3" cellspacing="1" width="100%" class="tborder"><tr><td class="row1"><span class="smalltext">
	<table border="0" cellpadding="2" cellspacing="0" width="100%"><tr><td width="1" align="left"><a href="#" onClick="javascript:switchGridTab(\'twmonth\', \'teamwork\');fetchData(\'twmonth\', \''. date("d-m-Y", getPreviousMonth($daystore[1], $daystore[2])) .'\');"><img src="'. $_SWIFT["themepath"] .'icon_back.gif" border="0" align="absmiddle" /></a></td>
	<td width="100%" align="center"><span class="ttexttitle">'. date("F Y", $dateline) .'</span></td>
	<td width="1" align="right"><a href="#" onClick="javascript:switchGridTab(\'twmonth\', \'teamwork\');fetchData(\'twmonth\', \''. date("d-m-Y", getNextMonth($daystore[1], $daystore[2])) .'\');"><img src="'. $_SWIFT["themepath"] .'icon_forward.gif" border="0" align="absmiddle" /></a></td></tr></table><BR />';

	$data .= '<table border="0" cellpadding="0" cellspacing="0" width="100%" class="calborder">'.SWIFT_CRLF;

	$daylist = array(1,2,3,4,5,6,0);

	$colspan = 2+(count($daylist)*2);
	$splitwidth = round(100/count($daylist));

	$data .= '<tr class="calhrbg"><td width="60" style="PADDING: 3px;" class="calhrbg"><span class="tabletitle">'. $_SWIFT["language"]["week"] .'</span></td><td width="1" class="calendarsplitter"><img src="'. $_SWIFT["themepath"] .'space.gif" border="0" width="1" height="1" /></td>'.SWIFT_CRLF;

	foreach ($daylist as $key=>$val)
	{
		$kk = $val;
		// Sunday
		if ($kk == 0)
		{
			$daydateline = $startweekdateline-86400;
		} else if ($kk == 1) {
			$daydateline = $startweekdateline;
		} else {
			$daydateline = $startweekdateline+(($kk-1)*86400);
		}

		if (in_array($kk, $daylist))
		{
			$data .= '<td width="'. $splitwidth .'%" align="center">'.SWIFT_CRLF;
			$data .= '<span class="tabletitle">'. date("l", $daydateline) .'</span>'.SWIFT_CRLF;
			$data .= '</td>'.SWIFT_CRLF;
			if ($kk != $daylist[count($daylist)-1])
			{
				$data .= '<td width="1" class="calendarsplitter"><img src="'. $_SWIFT["themepath"] .'space.gif" border="0" width="1" height="1" /></td>'.SWIFT_CRLF;
			}
		}
	}
	$data .= '</tr>'.SWIFT_CRLF;

	$week = date("W", $dateline);

	// Itterate the weeks
	for ($ii=0; $ii<6; $ii++)
	{
		$data .= '<tr class="calhrbg" height="80"><td width="60" align="right" valign="top" style="PADDING: 3px;" class="calinactivehour"><span class="tabletitle">'. $week .'</span></td><td width="1" class="calendarsplitter"><img src="'. $_SWIFT["themepath"] .'space.gif" border="0" width="1" height="1" /></td>'.SWIFT_CRLF;

		foreach ($daylist as $key=>$val)
		{
			$kk = $val;
			// Sunday
			if ($kk == 0)
			{
				$daydateline = $weekdateline+(6*86400);
			} else if ($kk == 1) {
				$daydateline = $weekdateline;
			} else {
				$daydateline = $weekdateline+(($kk-1)*86400);
			}

			$day = getStrDayRep($kk);

			if (in_array($kk, $daylist))
			{
				if ($_schedule[$day."_enabled"] == 1) {
					$tdclass = "calactivehour";
				} else {
					$tdclass = "calinactivehour";
				}

				if (date("m", $daydateline) != $currentmonth)
				{
					$itemclass = "disabledtext";
				} else if (date("d-m-Y", $daydateline) == edate("d-m-Y")) {
					$itemclass = "tabletitle";
					$tdclass = "calhrbg";
				} else {
					$itemclass = "smalltext";
				}

				$data .= '<td width="'. $splitwidth .'%" style="PADDING: 4px;" align="right" valign="top" class="'. $tdclass .'">'.SWIFT_CRLF;
 				$data .= '<a href="index.php?_m=teamwork&_a=insertevent&startdateline='. $daydateline .'"><span class="'. $itemclass .'">'.date("d", $daydateline).'</span></a>'.SWIFT_CRLF;
				$data .= renderVerticalEventBlocks($_events, $daydateline, ($daydateline+86399), false, $_schedule);
 				$data .= '</td>'.SWIFT_CRLF;
 				if ($kk != $daylist[count($daylist)-1])
				{
					$data .= '<td width="1" class="calendarsplitter"><img src="'. $_SWIFT["themepath"] .'space.gif" border="0" width="1" height="1" /></td>'.SWIFT_CRLF;
				}
			}
		}

		if ($ii != 5)
		{
			$data .= '<tr height="1" class="calendarsplitter"><td colspan="'. $colspan .'"><img src="'. $_SWIFT["themepath"] .'space.gif" border="0" width="1" height="1" /></td></tr>';
		}

		$data .= '</tr>'.SWIFT_CRLF;
		$week++;
		$weekdateline += 7*86400;
	}
	$data .= '</table>';

	$data .= '</span></td></tr></table><BR />';

	return $data;
}

/**
* Get the Previous Month
*/
function getPreviousMonth($month, $year)
{
	if ($month == 1)
	{
		$newmonth = 12;
		$newyear = $year-1;
	} else {
		$newmonth = $month-1;
		$newyear = $year;
	}
	return mktime(0,0,0,$newmonth, 1, $newyear);
}

/**
* Get the Next Month
*/
function getNextMonth($month, $year)
{
	if ($month == 12)
	{
		$newmonth = 1;
		$newyear = $year+1;
	} else {
		$newmonth = $month+1;
		$newyear = $year;
	}

	return mktime(0,0,0,$newmonth, 1, $newyear);
}

/**
* Gets the variable representation for given number
*/
function getStrDayRep($day)
{
	$days = array (0 => "sunday", 1 => "monday", 2 => "tuesday", 3 => "wednesday", 4 => "thursday", 5 => "friday", 6 => "saturday");
	return $days[$day];
}

/**
* Load the staff schedule
*/
function getStaffSchedule()
{
	global $dbCore, $_SWIFT;

	return $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."staffschedules` WHERE `staffid` = '". intval($_SWIFT["staff"]["staffid"]) ."';");
}

/**
* Return Unix timestamp for hour on curent day
*/
function returnHourDateline($firsthr, $dateline)
{
	// We always expect to have a 24 hr format
	$hrtime1 = explode(":", $firsthr);

	$hrtimeresult1 = mktime($hrtime1[0], $hrtime1[1], 0, date("m", $dateline), date("d", $dateline), date("Y", $dateline));

	return $hrtimeresult1;
}

/**
* Load the Events between the given timeline
*/
function loadCalendarEvents($starttimeline, $endtimeline)
{
	global $dbCore, $_SWIFT;

	$_events = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."calendarevents` WHERE ((`eventtype` = '". SWIFTPUBLIC ."') OR (`eventtype` = '". SWIFTPRIVATE ."' AND `staffid` = '". intval($_SWIFT["staff"]["staffid"]) ."')) AND (`startdateline` < '". intval($endtimeline) ."' AND `enddateline` > '". intval($starttimeline) ."');");
 	while ($dbCore->nextRecord())
 	{
		$_events[$dbCore->Record["calendareventid"]] = $dbCore->Record;
	}

	return $_events;
}

/**
* Render the Event Blocks in Horizontal Order
*/
function renderHorizontalEventBlocks($_events, $starttimeline, $endtimeline)
{
	global $_SWIFT;

	$data .= '<table border="0" cellpadding="0" cellspacing="0" width="100%"><tr>';
	foreach ($_events as $key=>$val)
 	{
		// Display if this event is within the designated boundaries
		if ( $val["startdateline"] < $endtimeline && $val["enddateline"] > $starttimeline )
		{
			$data .= '<td align="left" valign="top"><div style="PADDING: 3px;"><table border="0" cellpadding="3" cellspacing="0" width="150" class="calborder" onMouseOver="javascript:this.className=\'calborderhover\';" onMouseOut="javascript:this.className=\'calborder\';" onClick="javascript:window.location.href=\'index.php?_m=teamwork&_a=editevent&calendareventid='. $val["calendareventid"] .'\';" style="CURSOR: pointer;">';
			$data .= '<tr><td align="left" valign="top" class="calhrbg"><span class="smalltext">';
			if ($val["isalldayevent"] == "0")
			{
				$data .= '<span class="grayedtext">'.date("H:i", $val["startdateline"])." - ".date("H:i", $val["enddateline"])."</span><BR />";
			}
			$data .= iif($val["activitytype"]==ACTIVITY_CALL, '<img src="'. $_SWIFT["themepath"] .'icon_eventphone.gif" border="0" align="absmiddle" />&nbsp;').htmlspecialchars($val["subject"])."";
			if ($val["ownerstaffid"] != $_SWIFT["staff"]["staffid"])
			{
				$data .= '<BR />'.$_SWIFT["language"]["evowner"]." ".htmlspecialchars($_SWIFT["staffcache"][$val["ownerstaffid"]]["fullname"]);
			}
			if (!empty($val["location"]))
			{
				$data .= '<BR />'.$_SWIFT["language"]["evlocation"]." ".htmlspecialchars($val["location"]);
			}
			if (!empty($val["calendarcategoryid"]))
			{
				$data .= '<BR />'.$_SWIFT["language"]["efcategory"]." ".htmlspecialchars($_SWIFT["calendarcategorycache"][$val["calendarcategoryid"]]["title"]);
			}
			if (!empty($val["calendarlabelid"]))
			{
				$data .= '<BR />'.$_SWIFT["language"]["eflabel"].' <font color="'. $_SWIFT["calendarlabelcache"][$val["calendarlabelid"]]["labelcolorcode"] .'">'.htmlspecialchars($_SWIFT["calendarlabelcache"][$val["calendarlabelid"]]["title"]).'</font>';
			}
			if (!empty($val["calendarstatusid"]))
			{
				$data .= '<BR />'.$_SWIFT["language"]["efstatus"].' <font color="'. $_SWIFT["calendarstatuscache"][$val["calendarstatusid"]]["statuscolorcode"] .'">'.htmlspecialchars($_SWIFT["calendarstatuscache"][$val["calendarstatusid"]]["title"]).'</font>';
			}
			$data .= '</span></td></tr>';
			$data .= '</table></div></td>';
		}
	}
	$data .= '</tr></table>';

	return $data;
}
/**
* Render the Event Blocks in Vertical Order
*/
function renderVerticalEventBlocks($_events, $starttimeline, $endtimeline, $showdetails = true, $_schedule = false)
{
	global $_SWIFT;

	$headerdisplay = false;

//	$data .= SWIFT_CRLF."<!-- BEGIN BLOCK -->".SWIFT_CRLF;
	$eventcount = 0;

	 	foreach ($_events as $key=>$val)
 	{
		// Display if this event is within the designated boundaries
		if ( $val["startdateline"] < $endtimeline && $val["enddateline"] > $starttimeline )
		{
			if (!$headerdisplay)
			{
				$day = getStrDayRep(date("w", $val["startdateline"]));
				$tdclass = "calhrbg";
				if ($_schedule[$day."_enabled"] == 1 && $showdetails == false) {
					$tdclass = "calactivehour";
				} else if ($_schedule[$day."_enabled"] == 0 && $showdetails == false) {
					$tdclass = "calinactivehour";
				}

				if (date("d-m-Y", $val["startdateline"]) == edate("d-m-Y")) {
					$tdclass = "calhrbg";
				}

				$data .= '<div style="PADDING: 3px;"><table border="0" cellpadding="'. iif($showdetails,"3", "0") .'" cellspacing="0" width="100%"'. iif($showdetails, ' class="calborder"') .'><tr><td align="left" valign="top" class="'. $tdclass .'"><table border="0" cellpadding="0" cellspacing="0" width="100%">';

				$headerdisplay = true;
			}

			$data .= '<tr><td align="left" valign="top">';

			if ($eventcount > 0)
			{
				$data .= '<HR class="calhr" />';
			}

			$data .= '<div class="smalltext" onMouseOver="javascript:this.className=\'calitemhover\';" onMouseOut="javascript:this.className=\'smalltext\';" onClick="javascript:window.location.href=\'index.php?_m=teamwork&_a=editevent&calendareventid='. $val["calendareventid"] .'\';" style="CURSOR: pointer;">';

			if ($val["isalldayevent"] == "0" && $showdetails == true)
			{
				$data .= '<span class="grayedtext">'.date("H:i", $val["startdateline"])." - ".date("H:i", $val["enddateline"])."</span><BR />";
			}
			$data .= htmlspecialchars($val["subject"])."<BR />";
			if ($val["ownerstaffid"] != $_SWIFT["staff"]["staffid"] && $showdetails == true)
			{
				$data .= $_SWIFT["language"]["evowner"]." ".htmlspecialchars($_SWIFT["staffcache"][$val["ownerstaffid"]]["fullname"]);
			}
			if (!empty($val["location"]) && $showdetails == true)
			{
				$data .= $_SWIFT["language"]["evlocation"]." ".htmlspecialchars($val["location"]);
			}
			$data .= '</div></td></tr>';

			$eventcount++;
		}
	}

	if (!empty($data))
	{
		$data .= '</table></td></tr></table></div>';
	}

//	$data .= SWIFT_CRLF."<!-- END BLOCK -->".SWIFT_CRLF;

	return $data;
}

/**
* Render the Event Insert Form
*/
function renderEventForm($type)
{
	global $dbCore, $_SWIFT;

	$loadingdata = '<table border="0" cellpadding="3" cellspacing="1" width="100%" class="tborder"><tr><td class="row1"><span class="smalltext"><img src="'. $_SWIFT["themepath"] .'loadingcircle.gif" border="0" align="absmiddle" />&nbsp;'. $_SWIFT["language"]["loading"] .'</span></td></tr></table><BR /> ';

	printFormStart("efform", "index.php", "POST");
	echo '<table cellspacing="0" cellpadding="0" border="0" width="100%" id="caltableopt"><tr style="height: 1em"><td align="left"><div id="calopt"><ul id="tab">
	
	<li><a class="currenttab" href="#" onClick="this.blur(); switchGridTab(\'efgeneral\', \'eventform\');" id="efgeneral" title="'. $_SWIFT["language"]["general"] .'">'. $_SWIFT["language"]["general"] .'</a></li>
	<li><a href="#" onClick="this.blur(); switchGridTab(\'efmisc\', \'eventform\');" id="efmisc" title="'. $_SWIFT["language"]["misc"] .'">'. $_SWIFT["language"]["misc"] .'</a></li>
	<li><a href="#" onClick="this.blur(); switchGridTab(\'efcustom\', \'eventform\');" id="efcustom" title="'. $_SWIFT["language"]["custom"] .'">'. $_SWIFT["language"]["custom"] .'</a></li>
	</ul></div></td></tr>'.SWIFT_CRLF;

	echo '<tr style="height: 1em"><td align="left">'.SWIFT_CRLF;

	$buttontext = iif($type==INSERT, $_SWIFT["language"]["insert"], $_SWIFT["language"]["update"]);

	// ======= GENERAL TAB =======
	$eventtype = '<label for="eventtypeyes">'. '<input type="radio" name="eventtype" class="swiftradio" onClick="javascript:document.efform.ownerstaffid.disabled=false;" id="eventtypeyes" value="public"'. iif($_POST["eventtype"]==SWIFTPUBLIC||empty($_POST["eventtype"]), " checked") .' />'.$_SWIFT["language"]["public"].'</label>'.SWIFT_CRLF;
	$eventtype .= '<label for="eventtypeno">'. '<input type="radio" name="eventtype" id="eventtypeno" onClick="javascript:document.efform.ownerstaffid.disabled=true;" value="private"'. iif($_POST["eventtype"]==SWIFTPRIVATE, " checked") .' />'.$_SWIFT["language"]["private"].'</label>'.SWIFT_CRLF;

	$infolist[] = array($_SWIFT["language"]["eftype"], iif($type==DISPLAY, iif($_POST["eventtype"]==SWIFTPUBLIC, $_SWIFT["language"]["public"], $_SWIFT["language"]["private"]), $eventtype));

	$owner = '<select name="ownerstaffid" id="ownerstaffid" class="swiftselect"'. iif($_POST["eventtype"]==SWIFTPRIVATE, " disabled") .'>';
	foreach ($_SWIFT["staffcache"] as $key=>$val)
	{
		$owner .= '<option value="'. $val["staffid"] .'"'. iif($val["staffid"]==$_POST["ownerstaffid"]||($type==INSERT&&$_SWIFT["staff"]["staffid"]==$val["staffid"]), " selected") .'>'. htmlspecialchars($val["fullname"]) .'</option>';
	}
	$owner .= '</select>';
	$infolist[] = array($_SWIFT["language"]["efowner"], iif($type==DISPLAY, $_SWIFT["staffcache"][$_POST["ownerstaffid"]]["fullname"], $owner));

	unset($_startline);
	if ($type == INSERT && !empty($_POST["startdateline"]))
	{
		$_startline = calenderDateToDateline($_POST["startdateline"]);
	} else if ($type == EDIT && !empty($_POST["startdateline"])) {
		$_startline = intval($_POST["startdateline"]);
	}

	$_startdateline = iif(!empty($_GET["startdateline"]), $_GET["startdateline"], $_startline);
	$infolist[] = array($_SWIFT["language"]["efstart"], iif($type==DISPLAY, iif(!empty($_POST["startdateline"]), iif($_SWIFT["settings"]["dt_caltype"]=="us", date("m/d/Y H:i", $_POST["startdateline"]), date("d/m/Y H:i", $_POST["startdateline"]))), '<input type="text" name="startdateline" id="startdateline" onclick="return showCalendar(\'startdateline\', \''. iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y") .'\');" size="12" readonly="1" value="'. iif(!empty($_startdateline), iif($_SWIFT["settings"]["dt_caltype"]=="us", date("m/d/Y", $_startdateline), date("d/m/Y", $_startdateline))) .'" class="swifttext"/>&nbsp;<img src="'. $_SWIFT["themepath"] .'calendar.gif" onclick="return showCalendar(\'startdateline\', \''.iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y").'\');" style="cursor: pointer;" align="absmiddle"/>&nbsp;<input type="text" name="startdatelinetime" id="startdatelinetime" size="5" value="'. iif(!empty($_startdateline), date("H:i", $_startdateline), "00:00") .'" class="swifttext" id="startdatelinetime" style="'. iif($_POST["isalldayevent"]==1, "DISPLAY: none;") .'" />'));

	unset($_endline); unset($_endlinetime);
	if ($type == INSERT && !empty($_POST["enddateline"]))
	{
		$_endline = calenderDateToDateline($_POST["enddateline"]);
		$_endlinetime = calenderDateTimeToDateline($_POST["enddateline"], $_POST["enddatelinetime"]);
	} else if ($type == EDIT && !empty($_POST["enddateline"])) {
		$_endline = intval($_POST["enddateline"]);
		$_endlinetime = $_POST["enddateline"];
	}


	
	$infolist[] = array($_SWIFT["language"]["efend"], iif($type==DISPLAY, iif(!empty($_POST["enddateline"]), iif($_SWIFT["settings"]["dt_caltype"]=="us", date("m/d/Y H:i", $_POST["enddateline"]), date("d/m/Y H:i", $_POST["enddateline"]))), '<input type="text" name="enddateline" id="enddateline" onclick="return showCalendar(\'enddateline\', \''. iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y") .'\');" size="12" readonly="1" value="'. iif(!empty($_POST["enddateline"]),  iif($_SWIFT["settings"]["dt_caltype"]=="us", date("m/d/Y", $_endline), date("d/m/Y", $_endline))) .'" class="swifttext"/>&nbsp;<img src="'. $_SWIFT["themepath"] .'calendar.gif" onclick="return showCalendar(\'enddateline\', \''. iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y") .'\');" style="cursor: pointer;" align="absmiddle"/>&nbsp;<input type="text" name="enddatelinetime" id="enddatelinetime" size="5" value="'. iif(!empty($_endlinetime), date("H:i", $_endlinetime), "00:00") .'" class="swifttext" id="enddatelinetime" style="'. iif($_POST["isalldayevent"]==1, "DISPLAY: none;") .'" />'));
	$infolist[] = array($_SWIFT["language"]["efalldayevent"], iif($type==DISPLAY, iif($_POST["isalldayevent"]==1,$_SWIFT["language"]["yes"],$_SWIFT["language"]["no"]), '<input type="checkbox" class="swifttext" name="isalldayevent" onClick="javascript:if (this.checked==true) {hideObject(\'startdatelinetime\'); hideObject(\'enddatelinetime\');document.efform.startdatelinetime.value=\'00:00\';document.efform.enddatelinetime.value=\'00:00\'; } else {displayObject(\'startdatelinetime\'); displayObject(\'enddatelinetime\');}" value="1"'. iif($_POST["isalldayevent"]=="1"," checked") .' />'));
	$calendarcategory = '<select name="calendarcategoryid" class="swiftselect">';
	$calendarcategory .= '<option value="0" style="COLOR:'. "#666666" .';"'. iif($_POST["calendarcategoryid"]==0, " selected") .'>'. htmlspecialchars($_SWIFT["language"]["efnone"]) .'</option>';
	foreach ($_SWIFT["calendarcategorycache"] as $key=>$val)
	{
		if ($val["categorytype"] == CATEGORY_EVENT)
		{
			$calendarcategory .= '<option value="'. $val["calendarcategoryid"] .'"'. iif($val["calendarcategoryid"]==$_POST["calendarcategoryid"], " selected") .'>'. htmlspecialchars($val["title"]) .'</option>';
		}
	}
	$calendarcategory .= '</select>';
	$infolist[] = array($_SWIFT["language"]["efcategory"], iif($type==DISPLAY, $_SWIFT["calendarcategorycache"][$_POST["calendarcategoryid"]]["title"], $calendarcategory));

	$activitytype = '<label for="activitytypecall">'. '<input type="radio" name="activitytype" class="swiftradio" id="activitytypecall" value="'. ACTIVITY_CALL .'"'. iif($_POST["activitytype"]==ACTIVITY_CALL, " checked") .' />'.$_SWIFT["language"]["efcall"].'</label>'.SWIFT_CRLF;
	$activitytype .= '<label for="activitytypeapp">'. '<input type="radio" name="activitytype" id="activitytypeapp" value="'. ACTIVITY_APPOINTMENT .'"'. iif($_POST["activitytype"]==ACTIVITY_APPOINTMENT||empty($_POST["activitytype"]), " checked") .' />'.$_SWIFT["language"]["efappointment"].'</label>'.SWIFT_CRLF;

	$infolist[] = array($_SWIFT["language"]["efactivity"], iif($type==DISPLAY, iif($_POST["activitytype"]==ACTIVITY_CALL, $_SWIFT["language"]["efcall"], $_SWIFT["language"]["efappointment"]), $activitytype));
	$infolist[] = array($_SWIFT["language"]["eflocation"], iif($type==DISPLAY, $_POST["location"], '<input type="text" class="swifttext" name="location" value="'. $_POST["location"] .'" size="30" />'));

	$status = '<select name="calendarstatusid" class="swiftselect">';
	$status .= '<option value="0" style="COLOR:'. "#666666" .';"'. iif($_POST["calendarstatusid"]==0, " selected") .'>'. htmlspecialchars($_SWIFT["language"]["efnone"]) .'</option>';
	foreach ($_SWIFT["calendarstatuscache"] as $key=>$val)
	{
		if ($val["statustype"] == STATUS_EVENT)
		{
			$status .= '<option value="'. $val["calendarstatusid"] .'" style="COLOR:'. $val["statuscolorcode"] .';"'. iif($val["calendarstatusid"]==$_POST["calendarstatusid"], " selected") .'>'. htmlspecialchars($val["title"]) .'</option>';
		}
	}
	$status .= '</select>';
	$infolist[] = array($_SWIFT["language"]["efstatus"], iif($type==DISPLAY, '<font color="'. $_SWIFT["calendarstatuscache"][$_POST["calendarstatusid"]]["statuscolorcode"] .'">'.$_SWIFT["calendarstatuscache"][$_POST["calendarstatusid"]]["title"].'</font>', $status));

	$label = '<select name="calendarlabelid" class="swiftselect">';
	$label .= '<option value="0" style="COLOR:'. "#666666" .';"'. iif($_POST["calendarlabelid"]==0, " selected") .'>'. htmlspecialchars($_SWIFT["language"]["efnone"]) .'</option>';
	foreach ($_SWIFT["calendarlabelcache"] as $key=>$val)
	{
		if ($val["labeltype"] == LABEL_EVENT)
		{
			$label .= '<option value="'. $val["calendarlabelid"] .'" style="COLOR:'. $val["labelcolorcode"] .';"'. iif($val["calendarlabelid"]==$_POST["calendarlabelid"], " selected") .'>'. htmlspecialchars($val["title"]) .'</option>';
		}
	}
	$label .= '</select>';
	$infolist[] = array($_SWIFT["language"]["eflabel"], iif($type==DISPLAY, '<font color="'. $_SWIFT["calendarlabelcache"][$_POST["calendarlabelid"]]["labelcolorcode"] .'">'.$_SWIFT["calendarlabelcache"][$_POST["calendarlabelid"]]["title"].'</font>', $label));

	echo '<div id="tab_efgeneral" style="DISPLAY: block;" class="tabcontent">';
	echo '<table border="0" cellpadding="3" cellspacing="1" width="100%" class="tborder">';
	echo '<tr><td colspan="4" class="cleanrow"><table border="0" cellpadding="0" cellspacing="3" width="100%" class="smalltext"><tr><td width="1" nowrap><span class="smalltext">'.$_SWIFT["language"]["efsubject"].'</span></td><td>'.iif($type==DISPLAY, htmlspecialchars($_POST["subject"]), '<input type="text" class="swifttext" name="subject" value="'. $_POST["subject"] .'" size="30" style="WIDTH:98%;" />') .'</td></tr></table></td></tr>';
	renderSplitFields($infolist, "row2", "cleanrow");
	if ($type == INSERT || $type == EDIT)
	{
		printSubmitRow($buttontext, "4");
	}
	echo '</table><BR />';
	echo '</div>';

	// ======= MISC TAB =======
	unset($infolist);
	echo '<div id="tab_efmisc" style="DISPLAY: none;" class="tabcontent">';
	echo '<table border="0" cellpadding="3" cellspacing="1" width="100%" class="tborder">';
	renderSplitFields($infolist, "row2", "cleanrow");
	echo '<tr class="descrow">
<td class="descrow" align="left" valign="top" colspan="4">'. $_SWIFT["language"]["efdescription"] .'</td>
</tr>';
	echo '<tr><td colspan="4" class="cleanrow">'.iif($type==DISPLAY, nl2br(htmlspecialchars($_POST["contents"])), '<textarea style="WIDTH: 98%;" class="swifttextarea" name="body" cols="50" rows="6">'. htmlspecialchars($_POST["contents"]) .'</textarea>') .'</td></tr>';
	if ($type == INSERT || $type == EDIT)
	{
		printSubmitRow($buttontext, "4");
	}
	echo '</table><BR />';
	
	echo '</div>';

	// ======= CUSTOM FIELD TAB =======
	echo '<div id="tab_efcustom" style="DISPLAY: none;" class="tabcontent">';
	echo '<table border="0" cellpadding="3" cellspacing="1" width="100%" class="tborder">';

	ob_start();
	renderStaffCustomFields(CUSTOMFIELD_EVENT, false, iif($type==EDIT||$type==DISPLAY, $_POST["calendareventid"], 0));
	$contents = ob_get_contents();
	ob_end_clean();
	if (trim($contents) == "")
	{
		echo '<tr><td class="row2">'. $_SWIFT["language"]["nocferror"] .'</td></tr>';
	} else {
		echo $contents;
		if ($type == INSERT || $type == EDIT)
		{
			printSubmitRow($buttontext, "4");
		}
	}

	echo '</table><BR />';
	echo '</div>';

	echo '</td></tr></table>';
	printHiddenField("_m", "teamwork");
	printHiddenField("_a", iif($type==INSERT, "insertevent", "editevent"));
	printHiddenField("step", "1");
	printHiddenField("mode", "edit");
	if ($type == EDIT)
	{
		printHiddenField("calendareventid", $_POST["calendareventid"]);
	}
	printFormEnd();
}
?>